package cm.config;

import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author: yxh
 * @Description: 线程池配置
 * @Date: Created in 2022/9/1 10:43
 * @Modified By:
 */
@Configuration
@ConfigurationProperties(prefix = "pool")
@Setter
@EnableAsync
public class ThreadPoolConfig {
    /** 线程池中的核心线程数量,默认为1 */
    private int corePoolSize;
    /** 线程池中的最大线程数量 */
    private int maxPoolSize;
    /** 线程池中允许线程的空闲时间,默认为 60s */
    private int keepAliveTime;
    /** 线程池中的队列最大数量 */
    private int queueCapacity;
    /** 线程的名称前缀 */
    private static final String threadNamePrefix = "thread-call-runner-%d";

    @Bean("taskExecutor")
    @Lazy
    public ThreadPoolTaskExecutor thread(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveTime);
        executor.setThreadNamePrefix(threadNamePrefix);
        //拒绝策略
        // CallerRunsPolicy：由调用线程（提交任务的线程）处理该任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化
        executor.initialize();
        return executor;
    }
}
